from PIL import Image
from PIL import ImageFilter
import os
import matplotlib.pyplot as plt


class ImageProcessor:
    """定义基类，实现图片实例和参数列表，建立方法process"""
    def __init__(self, image, *args):
        self.image = image
        self.args = args

    def process(self):
        pass

###添加如下功能
class ImageProcessor_Grayscale(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_Grayscale,self).__init__(image, *args)
    def process(self):
        self.image=self.image.convert('L')
        return self.image

class ImageProcessor_resize(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_resize,self).__init__(image, *args)
    def process(self):
        self.image=self.image.resize(size=self.args)
        return self.image

class ImageProcessor_dim(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_dim,self).__init__(image, *args)
    def process(self):
        self.image=self.image.filter(ImageFilter.BLUR)
        return self.image

class ImageProcessor_EdgeExtraction(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_EdgeExtraction,self).__init__(image, *args)
    def process(self):
        self.image=self.image.filter(ImageFilter.CONTOUR)
        return self.image
####

"""取消这部分功能"""
# class GrayProcess(ImageProcessor):
#     """实现图像的灰度化处理"""
#     def __init__(self, image, *args):
#         ImageProcessor.__init__(self, image, *args)
#
#     def process(self):
#         self.image = self.image.convert("L")


class CropProcess(ImageProcessor):
    """实现图片的裁剪"""
    def __init__(self, image, *args):
        ImageProcessor.__init__(self, image, *args)
        self.args = args[0]

    def process(self):
        self.image = self.image.crop(self.args)


class BlurProcess(ImageProcessor):
    """实现图片的模糊处理滤镜"""
    def __init__(self, image, *args):
        ImageProcessor.__init__(self, image, *args)

    def process(self):
        self.image = self.image.filter(ImageFilter.GaussianBlur(5))


class EdgeProcess(ImageProcessor):
    """图片的边界提取"""
    def __init__(self, image, *args):
        ImageProcessor.__init__(self, image, *args)

    def process(self):
        self.image = self.image.filter(ImageFilter.CONTOUR)


class ImageShop:
    """"""
    def __init__(self, form, path):
        self.form = form
        self.path = path
        self.images = []
        self.processed_images = []

    def load_images(self):
        for file_name in os.listdir(self.path):
            if file_name.endswith('.'+self.form):
                img_path = self.path+"\\"+file_name
                im = Image.open(img_path)
                self.images.append(im)

    def __batch_ps(self, processor):
        """对图片进行统一处理"""
        for img in self.images:
            processor.image = img
            processor.process()
            self.processed_images.append(processor.image)

    def batch_ps(self, *args):
        for i in range(len(args)):
            if args[i][0] == "Gray":
                processor = GrayProcess(None,None)
            elif args[i][0] == "Crop":
                processor = CropProcess(None, args[i][1])
            elif args[i][0] == "Blur":
                processor = BlurProcess(None,None)
            elif args[i][0] == "Edge":
                processor = EdgeProcess(None,None)
            self.__batch_ps(processor)

    def save(self, out_path):
        for i, img in enumerate(self.processed_images):
            img.save(os.path.join(out_path, f"{i+1}.{self.form}"))
        # for image in self.processed_images:
        #     image.save(out_path)

    def display(self, rows, cols, img_size, max_size):
        fig = plt.figure(figsize=(img_size[0]*cols, img_size[1]*rows))
        for i in range(len(self.processed_images)):
            ax = fig.add_subplot(rows, cols, i+1)
            ax.imshow(self.processed_images[i],cmap=plt.get_cmap('gray'))
            ax.axis('off')   # 不显示坐标轴
        plt.savefig("D:\\Download\\New-Images\\total.jpg")
        plt.show()


class TestImageShop:
    """进行测试"""
    def __init__(self, path):
        self.path = path

    def runtest(self):
        shop = ImageShop("jpg", self.path)
        shop.load_images()
        shop.batch_ps(("Gray", ()),("Crop",(300,100,600,700)),("Blur", ()), ("Edge", ()))
        shop.save('D:\\Download\\New-Images')
        shop.display(4, 5, (4, 3), 5)


if __name__ == "__main__":
    test = TestImageShop('D:\\Download\\Images')
    test.runtest()
